package com.visionork.android.tai.model;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

import android.content.Context;
import android.util.Log;

import com.visionork.android.tai.TaiApp;
import com.visionork.android.tai.model.adapter.TaiAdapterBase;

public abstract class ProgramRepositoryBase implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected final ArrayList<Program> programs;
	protected TaiAdapterBase dataAdapter;

	protected ProgramRepositoryBase() {
		programs = new ArrayList<Program>();
	}

	public ArrayList<Program> getPrograms() {
		ArrayList<Program> result = getPrograms(true);
		return result;
	}

	public abstract ArrayList<Program> getPrograms(boolean useCache);

	public Program getProgramByUrlLink(String urlLink) {
		for (Program prog : programs) {
			if (prog.getUrlLink().equals(urlLink)) {
				return prog;
			}
		}
		return null;
	}

	public ArrayList<Program> getProgramsRef() {
		return programs;
	}

	public void AddProgram(Program prog) {
		programs.add(prog);
	}

	public synchronized void saveToFile() {
		Log.i("Tai", "save config to file.");
		if (programs != null && programs.size() > 0) {
			FileOutputStream fos = null;
			ObjectOutputStream out = null;
			try {
				fos = TaiApp.getAppContext().openFileOutput(
						getConfigFileName(), Context.MODE_PRIVATE);

				out = new ObjectOutputStream(fos);
				out.writeObject(programs);
				out.close();
			} catch (Throwable e) {
				e.printStackTrace();
			}

		}
	}

	@SuppressWarnings("unchecked")
	public synchronized void loadFromFile() {
		Log.i("Tai", "load config from file.");
		FileInputStream fis = null;
		ObjectInputStream in = null;
		try {
			fis = TaiApp.getAppContext().openFileInput(getConfigFileName());
			in = new ObjectInputStream(fis);
			Object fileObj = in.readObject();
			if (fileObj instanceof ArrayList<?>) {
				programs.clear();
				for (Program prog : (ArrayList<Program>) fileObj) {
					programs.add(prog);
				}
			}

			in.close();
		} catch (Exception e) {
			// TODO:
		}
		return;
	}

	protected void mergeData(
			Collection<? extends com.visionork.android.tai.model.Program> data) {
		for (Program prog : data) {
			if (!programs.contains(prog)) {
				/* add new one */
				programs.add(prog);
			} else {
				/* update old one */
				Program existProg = programs.get(programs.indexOf(prog));
				existProg.setTitle(prog.getTitle());
				existProg.setMeta(prog.getMeta());
			}
		}

		/* remove expired one */
		for (Program prog : programs) {
			if (!data.contains(prog)) {
				programs.remove(prog);

			}
		}
	}

	protected abstract String getConfigFileName();

	protected abstract TaiAdapterBase getDataAdapter();
}
